<template>
  <div class="imContainer" ref="loadingBox">
    <!-- 铃声标签 -->
    <div class="leftContainer">
      <!-- <div class="search_box">
        <el-input
          ref="suuggestInputComps"
          v-model.trim="inputValue"
          placeholder="搜索"
          @focus="isShowResultContent = true"
          @clear="isShowResultContent = false"
          @input="querySearch"
          @keydown.escape="handleEscapeKey"
          :prefix-icon="Search"
          clearable
        />
      </div> -->
      <el-scrollbar class="session_list" style="overflow: auto" tag="ul">
        <div class="listItem" @click="getSystemInfo">
          <div class="item_body item_left">
            <el-image style="width: 20px; height: 20px" :src="tipInfo.avator" fit="fill" class="img" />
          </div>
          <div class="item_body item_main">
            <div class="name">{{ tipInfo.name }}</div>
            <div class="last_msg_body">{{ tipInfo.title || "暂无消息通知" }}</div>
          </div>
          <div class="item_body item_right">
            <div class="time">{{ tipInfo.time }}</div>
          </div>
        </div>
        <!-- 普通会话 -->
        <template v-if="friendsList.length > 0">
          <li v-for="(item, index) in friendsList" :key="index" @click="selectUser(item)">
            <el-popover
              popper-class="conversation_popover"
              placement="bottom"
              trigger="contextmenu"
              :show-arrow="false"
              :offset="-10"
              :auto-close="5000"
            >
              <template #reference>
                <div
                  class="session_list_item"
                  :class="activeUser.userId === item.conversationId && item.conversationId ? 'active' : ''"
                >
                  <div class="item_body item_left">
                    <div class="session_other_avatar">
                      <el-avatar :size="42" :src="handleConversationAvatar(item)"> </el-avatar>
                      <div class="status" :class="getStatus(item.conversationId) ? 'online' : ''"></div>
                    </div>
                  </div>
                  <div class="item_body item_main">
                    <div class="name" :tooltip="handleConversationName(item)">
                      {{ handleConversationName(item) }}
                    </div>
                    <div class="last_msg_body">
                      {{ item.lastMessage && handleLastMsgContent(item.lastMessage) }}
                    </div>
                  </div>
                  <div class="item_body item_right">
                    <span class="time">{{ dateFormater("MM/DD/HH:mm", item?.lastMessage?.time) }}</span>
                    <span class="unReadNum_box" v-if="item.unReadCount >= 1">
                      <sup class="unReadNum_count" v-text="item.unReadCount >= 99 ? '99+' : item.unReadCount"></sup>
                    </span>
                  </div>
                </div>
              </template>
              <template #default>
                <div class="session_list_delete" @click="deleteCon(item)">删除会话</div>
              </template>
            </el-popover>
          </li>
        </template>
        <template v-else>
          <el-empty description="暂无最近会话" />
        </template>
      </el-scrollbar>
    </div>
    <div class="rightContainer">
      <div class="userInfo" v-if="activeType == 'user'">
        <div class="userName">{{ handleConversationName(activeUser) }}</div>
      </div>
      <div class="userInfo" v-if="activeType == 'system'">
        <div class="userName">系统通知</div>
      </div>
      <div class="tips" v-if="activeType == 'user' && showTips">
        <el-icon class="closeIcon" @click="showTips = false"><Close /></el-icon>
        <div v-for="(item, index) in tips" :key="index">
          {{ item.name }}
        </div>
      </div>
      <img :src="imageUrl" alt="" v-if="!activeType" />
      <div class="historyList" v-if="activeType == 'user'">
        <el-main class="chat_message_main">
          <el-scrollbar class="main_container" ref="messageContainer">
            <div class="innerRef">
              <div v-show="isMoreHistoryMsg" class="chat_message_tips">
                <div v-show="messages.length && messages[0].type !== 'inform'" class="load_more_msg">
                  <el-link
                    v-show="!loadingHistoryMsg"
                    :disabled="!isMoreHistoryMsg"
                    :underline="false"
                    @click="fechHistoryMessage()()"
                  >
                    加载更多
                  </el-link>
                  <el-link v-show="loadingHistoryMsg" disabled>消息加载中...</el-link>
                </div>
              </div>
              <messageList
                :message-data="messages"
                @scroll-message-list="scrollMessageList"
                :to-user-info="activeUser"
                :custom-data="customData"
                :loading="isLoading"
              />
            </div>
          </el-scrollbar>
        </el-main>
      </div>
      <div class="footerFunction" v-if="activeType == 'user'">
        <operateBox ref="inputBoxComp" :route_query_data="{}"></operateBox>
      </div>
      <div v-if="activeType == 'system'">
        <el-empty description="暂无消息通知" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ElLoading } from "element-plus";
const loadingBox = ref<any>(null);
type ElLoading = /*unresolved*/ any;
let loadingInstance: ElLoading;
const onStartLoading = () => {
  if (loadingInstance) return;
  loadingInstance = ElLoading.service({
    target: loadingBox.value,
    background: "#f7f7f7"
  });
  return loadingInstance;
};
const onLoadending = () => {
  loadingInstance?.close();
  loadingInstance = null;
};
import { useRoute } from "vue-router";
const route = useRoute();
import imageUrl from "@/assets/images/welcome.png";
import operateBox from "./components/ChatInputBox/operateBox.vue";
import messageList from "./components/messageBox/index.vue";
import { ref, reactive, computed, nextTick, watch, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import { useImStore } from "@/stores/modules/im";
import { SESSION_MESSAGE_TYPE, CUSTOM_MSG_EVENT_TYPE } from "./constant";
import { MESSAGE_TYPE } from "@/IM/constant";
import dateFormater from "./utils/dateFormater";
import _ from "lodash";
import { ElMessage } from "element-plus";
import { setStatus } from "@/api/modules/im";
const inputBoxComp = ref(null);
const suuggestInputComps = ref();
const inputValue = ref();
const isShowResultContent = ref(false);
const showTips = ref(true);
const tipInfo = reactive<any>({
  avator: "https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/pc/bell_icon.png",
  name: "消息通知",
  time: "",
  title: ""
});
const imStore = useImStore();
const friendsList = computed<any>(() => {
  return imStore.contacts || [];
});
const tips = reactive<any[]>([
  {
    name: "【安全提示】本应用仅用于环信产品功能开发测试，请勿用于非法用途。任何涉及转账、汇款、裸聊、网恋、网购退款、投资理财等统统都是诈骗，请勿相信！",
    value: "1"
  },
  {
    name: "【防骗提示】号码陌⽣勿轻接，虚拟电话设陷阱。",
    value: "2"
  }
]);
/* 消息相关 */
const loadingHistoryMsg = ref(false); //是否正在加载中
const isMoreHistoryMsg = ref(true); //加载文案展示为加载更多还是已无更多。
const notScrollBottom = ref(false); //是否滚动置底
const messageContainer = ref(null);
//获取历史记录
//首次进入加载消息，下拉也是加载消息，发送消息时不加载消息，切换用户时加载消息
const messages = computed<any>(() => {
  if (imStore.onLine && imStore.chatWith) {
    return imStore.historyMessages[imStore.chatWith]
      ? imStore.historyMessages[imStore.chatWith]
      : fechHistoryMessage("fistLoad")();
  } else {
    return [];
  }
});
watch(
  () => messages,
  () => {
    nextTick(() => {
      initCustomData();
      imStore.getMessageStatus(messages.value);
      if (notScrollBottom.value) {
        return;
      } else {
        setTimeout(() => {
          scrollMessageList("bottom");
        }, 300);
      }
    });
  },
  {
    deep: true,
    immediate: true
  }
);
import { getJobs, getFlexJobs, getInterviewinfos } from "@/api/modules/im";
let customData = reactive({});
let isLoading = ref(true);
const initCustomData = async () => {
  let jobIds1: any[] = []; //全职
  let jobIds2: any[] = []; //零工
  let jobIds3: any[] = []; //面试
  if (!messages.value.length) return;
  messages.value.map((item: any) => {
    if (
      item.type == "custom" &&
      item.customExts.id &&
      item.customExts.type === "job" &&
      !customData[item.customExts.id] &&
      jobIds1.indexOf(item.customExts.id) == -1
    ) {
      jobIds1.push(item.customExts?.id);
    }
    if (
      item.type == "custom" &&
      item.customExts.id &&
      item.customExts.type === "flexJob" &&
      !customData[item.customExts.id] &&
      jobIds2.indexOf(item.customExts.id) == -1
    ) {
      jobIds2.push(item.customExts?.id);
    }
    if (
      item.type == "custom" &&
      item.customExts.id &&
      item.customExts.type === "interview" &&
      !customData[item.customExts.id] &&
      jobIds3.indexOf(item.customExts.id) == -1
    ) {
      jobIds3.push(item.customExts?.id);
    }
  });
  isLoading.value = true;
  if (jobIds1.length) {
    let result1: any = await getJobs({
      jobIds: jobIds1
    });
    if (result1.data && result1.data.list) {
      result1.data.list.map(item => {
        customData[item.id] = item;
      });
    }
  }
  if (jobIds2.length) {
    let result2: any = await getFlexJobs({
      jobIds: jobIds2
    });
    if (result2.data) {
      result2.data.map(item => {
        customData[item.id] = item;
      });
    }
  }
  if (jobIds3.length) {
    let result3: any = await getInterviewinfos({
      ids: jobIds3
    });
    if (result3.data) {
      result3.data.map(item => {
        customData[item.id] = item;
      });
    }
  }
  isLoading.value = false;
};
const getStatus = id => {
  let isOnline = false;
  imStore.onLineStatus.map((item: any) => {
    if (item.uid == id) {
      if (Array.isArray(item.status)) {
        if (item.status.length) {
          isOnline = true;
        }
      } else {
        if (Object.keys(item.status).length) {
          isOnline = true;
        }
      }
    }
  });
  return isOnline;
};
const fechHistoryMessage = (loadType?: string) => {
  let result: any = [];
  result;
  return async () => {
    loadingHistoryMsg.value = true;
    notScrollBottom.value = true;
    if (loadType == "fistLoad") {
      result = await imStore.getHistoryMessage({
        cursor: -1
      });
      if (result.length == 10) {
        //返回数组有数据显示加载更多
        isMoreHistoryMsg.value = true;
      } else {
        //否则已无更多。
        isMoreHistoryMsg.value = false;
      }
      setTimeout(() => {
        scrollMessageList("bottom");
      }, 500);
    } else {
      const fistMessageId = messages.value[0] && messages.value[0].id;
      result = await imStore.getHistoryMessage({
        cursor: fistMessageId
      });
      if (result.length == 10) {
        //返回数组有数据显示加载更多
        isMoreHistoryMsg.value = true;
      } else {
        //否则已无更多。
        isMoreHistoryMsg.value = false;
      }
      scrollMessageList("normal");
    }
    loadingHistoryMsg.value = false;
    notScrollBottom.value = false;
    return result;
  };
};
//控制消息滚动
const scrollMessageList = (direction: string) => {
  //direction滚动方向 bottom向下滚动 normal向上滚动
  nextTick(() => {
    const messageNodeList = document.querySelectorAll(".messageList_box");
    const fistMsgElement = messageNodeList[0];
    const lastMsgElement = messageNodeList[messageNodeList.length - 1];
    //直接滚动置底
    if (direction === "bottom") {
      lastMsgElement && lastMsgElement.scrollIntoView(false);
    }
    //保持当前的消息位于当前可视窗口
    if (direction === "normal") {
      fistMsgElement.scrollIntoView(true);
    }
  });
};

const getSystemInfo = () => {
  activeType.value = "system";
  activeUser.value = {};
};
let activeUser = ref<any>({});
const activeType = ref<string>();
const selectUser = _.debounce((item: { conversationId: any }) => {
  activeType.value = "user";
  activeUser.value = item;
  imStore.$patch({
    chatWith: item.conversationId
  });
  imStore.setChannelRead();
  imStore.clearReadMount(item.conversationId);
  onLoadending();
}, 300);
const handleConversationAvatar = item => {
  return item.avator || "https://qwzls.oss-cn-hangzhou.aliyuncs.com/recruit/static/message/theme22x.png";
};
const handleConversationName = item => {
  if (item.companyName) {
    return item.companyName + "(" + (item.name || item.conversationId) + ")";
  } else {
    return item.name || "游客（" + item.conversationId + "）";
  }
};
const handleLastMsgContent = computed(() => {
  return msgBody => {
    const { type, msg } = msgBody;
    let resultContent = "";
    //如果消息类型，在预设非展示文本类型中，就返回预设值
    if (msgBody.ext === "callBack") {
      resultContent = imStore.userId == msgBody.from ? "[您撤回了一条消息]" : "[对方撤回了一条消息]";
    } else {
      if (SESSION_MESSAGE_TYPE[type]) {
        resultContent = SESSION_MESSAGE_TYPE[type];
      } else if (type === MESSAGE_TYPE.CUSTOM) {
        //如果为自定义类型消息就匹配自定义消息对应的lastmsg文本
        if (msgBody.customEvent) {
          resultContent = CUSTOM_MSG_EVENT_TYPE[msgBody.customExts.type];
        }
      } else {
        resultContent = msg;
      }
    }
    return resultContent;
  };
});
const querySearch = (e: { target: { value: any } }) => {
  if (e.target.value) {
    isShowResultContent.value = true;
  }
};
const handleEscapeKey = () => {
  isShowResultContent.value = false;
};
const deleteCon = async item => {
  let info = await imStore.deleteContacts(item.conversationId);
  if (info) {
    ElMessage.success("刪除成功");
  }
};
onMounted(async () => {
  if (route.query.userId) {
    onStartLoading();
    setTimeout(() => {
      nextTick(async () => {
        let info = await imStore.getConversation(route.query.userId);
        // 可以加到state中设置头部标题
        // if (info.companyName) {
        //   route.meta.title = info.companyName + "(" + (info.name || info.conversationId) + ")";
        // } else {
        //   route.meta.title = info.name || "游客（" + info.conversationId + "）";
        // }
        // console.log(route.meta.title)
        selectUser(info);
      });
    }, 1000);
  }
});
</script>

<style lang="scss">
.imContainer {
  ul,
  ol {
    padding: 0 !important; /* 移除列表内边距 */
    margin: 0 !important; /* 移除列表外边距 */
    list-style-type: none !important; /* 移除列表项目符号 */
  }
  li {
    padding: 0 !important; /* 重置li的左右内边距 */
    margin: 0 !important; /* 重置li的上下外边距 */
    list-style-type: none !important; /* 移除列表项目符号 */
  }
}
</style>
<style lang="scss" scoped>
.imContainer {
  display: flex;
  height: 100%;
  .leftContainer {
    width: 324px;
    height: 100%;
    background: #cfdbf171;
    flex-shrink: 0;
    .search_box {
      box-sizing: border-box;
      width: 100%;
      height: 60px;
      padding: 14px 20px;
      overflow: hidden;
      background: #f8f8f8;
    }
    .listItem {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: flex-start;
      height: 66px;
      cursor: pointer;
      background: #ffffff;
      border-bottom: 1px solid var(--el-border-color);
      &:hover {
        background: #e5e5e5;
      }
      .item_body {
        display: flex;
        height: 100%;
      }
      .item_left {
        flex-direction: row;
        flex-shrink: 0;
        align-items: center;
        justify-content: center;
        width: 34px;
        height: 34px;
        margin-right: 10px;
        margin-left: 14px;
        background-color: #ff9663;
        border-radius: 50%;
      }
      .item_main {
        flex-direction: column;
        align-items: flex-start;
        justify-content: space-around;
        width: 225px;
        max-width: 225px;
        height: 50px;
      }
      .name {
        min-width: 56px;
        max-width: 180px;
        height: 17px;
        overflow: hidden;
        font-size: 14px;
        font-weight: 400;
        color: #333333;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .last_msg_body {
        max-width: 185px;
        height: 17px;
        overflow: hidden;
        font-size: 12px;
        font-weight: 400;
        line-height: 17px;
        color: #a3a3a3;
        text-overflow: ellipsis;
        letter-spacing: 0.3px;
        white-space: nowrap;
      }
      .last_msg_body_mention {
        font-size: 12px;
        font-weight: 700;
        line-height: 17px;
        color: red;
      }
      .time {
        font-size: 10px;
        font-weight: 400;
        line-height: 14px;
        color: #a3a3a3;
        letter-spacing: 0.25px;
      }
      .item_right {
        flex-direction: column;
        align-items: flex-end;
        width: 25%;
        height: 50px;
        margin-right: 10px;
        .unReadNum_count {
          box-sizing: border-box;
          display: inline-block;
          min-width: 20px;
          height: 20px;
          padding: 0 6px;
          font-size: 12px;
          font-weight: 400;
          line-height: 20px;
          color: #ffffff;
          text-align: center;
          white-space: nowrap;
          background: #f5222d;
          border-radius: 10px;
        }
      }
    }
  }
  .session_list {
    height: calc(100% - 60px);
    overflow: auto;
  }
  .session_list .session_list_item {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    height: 66px;
    color: var(--el-color-primary);
    cursor: pointer;
    background: #ffffff;
    border-bottom: 1px solid var(--el-border-color);
    &:hover {
      background: #e5e5e5;
    }
    .item_body {
      display: flex;
      height: 100%;
    }
    .item_left {
      flex-direction: row;
      align-items: center;
      justify-content: center;
      margin-right: 10px;
      margin-left: 14px;
      .session_other_avatar {
        position: relative;
        .status {
          width: 10px;
          height: 10px;
          border-radius: 50%;
          background-color: #ccc;
          position: absolute;
          right: 4px;
          bottom: 4px;
        }
        .online {
          background-color: rgb(6, 241, 37);
        }
      }
    }
    .item_main {
      flex-direction: column;
      align-items: flex-start;
      justify-content: space-between;
      width: 225px;
      max-width: 225px;
      height: 40px;
      .name {
        min-width: 56px;
        max-width: 180px;
        height: 17px;
        overflow: hidden;
        font-size: 14px;
        font-weight: 400;

        /* identical to box height */
        color: #333333;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .last_msg_body {
        max-width: 185px;
        height: 17px;
        overflow: hidden;
        font-size: 12px;
        font-weight: 400;
        line-height: 17px;
        color: #a3a3a3;
        text-overflow: ellipsis;
        letter-spacing: 0.3px;
        white-space: nowrap;
      }
      .last_msg_body_mention {
        font-size: 12px;
        font-weight: bold;
        line-height: 17px;
        color: red;
      }
    }
    .item_right {
      flex-direction: column;
      align-items: flex-end;
      width: 25%;
      height: 34px;
      margin-right: 10px;
      .time {
        font-size: 10px;
        font-weight: 400;
        line-height: 14px;
        color: #a3a3a3;
        letter-spacing: 0.25px;
      }
      .unReadNum_box {
        vertical-align: middle;
        .unReadNum_count {
          box-sizing: border-box;
          display: inline-block;
          min-width: 20px;
          height: 20px;
          padding: 0 6px;
          font-size: 12px;
          font-weight: normal;
          line-height: 20px;
          color: #ffffff;
          text-align: center;
          white-space: nowrap;
          background: #f5222d;
          border-radius: 10px;
        }
      }
    }
  }
  .active {
    background: #e5e5e5 !important;
  }
  .session_list .session_list_item + .list_item {
    margin-top: 10px;
  }
  .session_list_delete {
    cursor: pointer;
    transition: all 0.5s;
    &:hover {
      background: #e1e1e1;
    }
  }
  .conversation_popover {
    width: 80px !important;
    padding: 5px 3px !important;
    color: #333333 !important;
    text-align: center !important;
  }
  .rightContainer {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    width: 100%;
    height: 100%;
    background: #ffffff;
    border-left: 1px solid #e6e6e6;
    overflow: hidden;
    .userInfo {
      position: relative;
      display: flex;
      flex-direction: row;
      flex-shrink: 0;
      align-items: center;
      justify-content: space-between;
      height: 60px;
      padding-left: 20px;
      background: #f9f9f9;
      border-bottom: 1px solid #e6e6e6;
      .userName {
        overflow: hidden;
        font-family: "PingFang SC";
        font-size: 17px;
        font-style: normal;
        font-weight: 400;
        line-height: 20px;
        color: #333333;
        text-overflow: ellipsis;
        letter-spacing: 0.3px;
        white-space: nowrap;
      }
    }
    .tips {
      position: relative;
      padding: 12px 20px;
      font-family: "PingFang SC";
      font-size: 12px;
      font-style: normal;
      font-weight: 400;
      line-height: 18px;
      color: #ff8c39;
      text-align: justify;
      background-color: #fff4e6;
      border: none;
      .closeIcon {
        position: absolute;
        right: 15px;
        cursor: pointer;
      }
    }
    .historyList {
      position: relative;
      height: 100%;
      overflow: auto;
      background-color: #f9f9f9;
      .chat_message_main {
        height: 100%;
        padding: 0;
        background: #f9f9f9;
        .main_container {
          height: 100%;
          padding: 0 20px;

          // overflow-y: scroll;overflow-y
          .chat_message_tips {
            width: 100%;
            height: 30px;
            margin-top: 5px;
            line-height: 30px;
            text-align: center;
            .load_more_msg {
              width: 200px;
              height: 30px;
              margin: 0 auto;
              font-size: 13px;
              letter-spacing: 0.5px;
              background: rgb(114 112 112 / 14.3%);
              border-radius: 20px;

              // box-shadow: 1px 1px 1px 1px rgba(128, 128, 128, 0.193);box-shadow
            }
          }
        }
      }
    }
    .footerFunction {
      position: relative;
      height: 25%;
    }
  }
}
</style>
